package com.dingjun.dataBack.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ZipUtil;
import com.dingjun.dataBack.service.DataBackService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class DataBackServiceImpl implements DataBackService {

  private final static Logger logger = LoggerFactory.getLogger(DataBackServiceImpl.class);

    @Value("${data.back.backDir}")
    private String backupFilePath;

    @Value("${data.back.commandLocation}")
    private String commandLocation;

    @Value("${data.back.haloData}")
    private String haloData;

    @Value("${data.back.haloCurrentDir}")
    private String haloCurrentDir;


    @Scheduled(cron="0 0 */1 * * ?")//每小时执行一次
    public void back(){
        logger.info("定时任务开始执行------------------------");
        try {
            String fileName = new Date().getTime()+".sql";
            StringBuilder command = new StringBuilder();
            command.append(commandLocation)
                    .append(File.separator)
                    .append("mysqldump")
                    .append(" -uroot")
                    .append(" -pdsl190930")
                    .append(" -h154.3.2.63")
                    .append(" ")
                    .append(" halo extensions")
                    .append(" > ")
                    .append(backupFilePath)
                    .append(File.separator)
                    .append(fileName)
            .append(" --ssl-mode=DISABLE");
            logger.info("执行的命令："+command.toString());
            String commandType = getCommandType();
            logger.info("执行的命令：{}",commandType);
            ProcessBuilder processBuilder = new ProcessBuilder(commandType,"-c", command.toString());
            int flag = processBuilder.start().waitFor();
            if (flag == 0){
                deleteDir(backupFilePath,fileName);
                //备份halo数据
                zipFile();
            }else {
                logger.error("备份失败");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    /**
     * 压缩文件
     **/
    public void zipFile(){
        String fileName = new Date().getTime()+".zip";
        File file = ZipUtil.zip(haloCurrentDir, haloData+File.separator+fileName);
        if (file.exists()){
            logger.info("halo文件备份成功");
            deleteDir(haloData,fileName);

        }
    }

    /**
     * @param excludeFile 排除的文件
     **/
    public void deleteDir(String dir,String excludeFile){
        File file = new File(dir);
        if (!file.exists()){
            boolean flag = file.mkdir();
            if (flag){
                logger.info("备份文件夹创建成功");
            }
        }
        List<File> fileList = Convert.toList(File.class,file.listFiles());
        if (CollUtil.isNotEmpty(fileList)){
            for (File data : fileList) {
                if (!data.getName().equals(excludeFile)){
                    boolean delete = data.delete();
                    if (delete){
                        logger.info("删除历史文件成功");
                    }
                }
            }
        }
    }
    /**
     * 获取命令的执行类型
     **/
    public String getCommandType(){
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            return "cmd.exe";
        }
        return "bash";
    }
}
